package com.hongying;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;


/**
 * channel.waitForConfirms()普通发送方确认模式
 */
public class SendWaitForConfirms {


        public static void main(String[] args) {
            //创建连接工厂
            ConnectionFactory factory=new ConnectionFactory();
            //配置rabbitMQ的连接信息
            factory.setHost("192.168.174.129");
            factory.setPort(5672);
            factory.setUsername("root");
            factory.setPassword("123456");
            //定义连接
            Connection connection=null;
            //定义通道
            Channel channel=null;

            try {
                connection=factory.newConnection();
                channel=connection.createChannel();
                channel.queueDeclare("confirmQueue",true,false,false,null);
                channel.exchangeDeclare("directConfirmExchange","direct",true);
                channel.queueBind("confirmQueue","directConfirmExchange","confirmRoutingKey");
                String message="普通发送者确认模式的测试消息！";
                //启动发送者确认模式
                channel.confirmSelect();
                channel.basicPublish("directTransactionExchange","confirmRoutingKey",null,message.getBytes("utf-8"));
                /**
                 * 普通消息确认：
                 * 可以指定发送的超时时间，如果超过发送时间，则redis会利用定时任务补发消息
                 * 每次只能确认一条消息
                 * 发送一次，确认一次，效率不高。
                 */
                boolean flag=channel.waitForConfirms();
                System.out.println("消息发送成功"+flag);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if (channel!=null){
                    try {
                        channel.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (TimeoutException e) {
                        e.printStackTrace();
                    }
                }
                if (connection!=null){
                    try {
                        connection.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }


        }


}
